package com.example.controller;

import com.example.bean.UserInfoBean;
import com.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class UserController {
    // 使用ioc、di进行依赖注入
    @Autowired
    private IUserService userService;

    @RequestMapping("/login")
    public ModelAndView doLogin(UserInfoBean userInfoBean) {
        // 返回对象
        ModelAndView modelAndView = new ModelAndView();
        // 调用service层进行登录业务逻辑处理
        List<UserInfoBean> userInfoBeanList =  userService.queryForLogin(userInfoBean);
        // 判断是否登录成功
        if(userInfoBeanList != null && userInfoBeanList.size() > 0) {
            // 登录成功
            // 缓存登录成功的数据
            modelAndView.addObject("loginUser",userInfoBeanList.get(0));
            // 返回登录成功的视图名
            modelAndView.setViewName("login/main");
        } else {
            // 登录失败，返回登录页面
            modelAndView.setViewName("index");
        }
        // 返回视图
        return modelAndView;
    }

    // 在RESTFul编程中，只要controller中的方法返回的方法结果类型为 ResponseEntity 则，该方法就会进行ajax处理
    // 不会进行默认的视图解析
    @RequestMapping("/doAjaxQuery")
    public ResponseEntity<List<UserInfoBean>> doAjaxQuery(UserInfoBean userInfoBean) {
        System.out.println("userInfoBean:"+userInfoBean.toString());
        // 调用service层进行查询操作
        List<UserInfoBean> userInfoBeanList = userService.queryUserInfoByParams(userInfoBean);
        return new ResponseEntity<List<UserInfoBean>>(userInfoBeanList, HttpStatus.OK);
    }
}
